/**
 * 
 */
package com.eyolas.passwordmanager.activities;

import java.sql.SQLException;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.eyolas.passwordmanager.base.PasswordManagerBaseActivity;
import com.eyolas.passwordmanager.dao.CategoryDao;
import com.eyolas.passwordmanager.model.Category;
import com.eyolas.passwordmanager.utils.StringUtils;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.ViewById;
import com.eyolas.passwordmanager.R;

/**
 * @author Eyolas
 * @date 30 mai 2012
 */
@EActivity(R.layout.create_category)
public class CreateCategory extends PasswordManagerBaseActivity{
	@ViewById(R.id.editTextCategoryName)
	public EditText _categoryName;
	private CategoryDao _categoryDao;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			_categoryDao = getHelper().getCategoryDao();
		} catch (SQLException e) {
			Log.e(CreateCategory.class.getName(), "Error on get dao: " + e);
			finish();
		}
	}
	
	@Click(R.id.buttonValidCategory)
	public void onValid(){
		String categoryName = _categoryName.getText().toString().toLowerCase();
		try {
			if (!StringUtils.isNotBlank(categoryName)) {
				Toast.makeText(this, getString(R.string.categoryNameRequired), Toast.LENGTH_LONG).show();
				return;
			} else if(_categoryDao.categoryExist(categoryName)) {
				Toast.makeText(this, getString(R.string.categoryExist), Toast.LENGTH_LONG).show();
				return;
			}
			_categoryDao.create(new Category(categoryName));
			Toast.makeText(this, getString(R.string.categoryCreateSuccess), Toast.LENGTH_SHORT).show();
			Intent intent = new Intent();
			setResult(ListCategory.RELOAD_LIST, intent);
			finish();
		} catch (Exception e) {
			Log.e(CreateCategory.class.getName(), "Error : " + e);
			return;
		}
	}
	
	@Click(R.id.buttonCancel)
	public void onCancel(){
		finish();
	}
}
